<template>
    <AdminSkeleton>
        <template #header>
            <div class="params-form">
                <el-form :model="paramsForm" label-width="auto">
                    <el-form-item label="线路:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                            <el-select v-model="paramsForm.lines" clearable placeholder="可留空" size="small"
                                style="width: 150px" multiple collapse-tags collapse-tags-tooltip @change="changeLines"
                                @visible-change="getLines">
                                <template #header>
                                    <el-checkbox v-model="lineCheckAll" :indeterminate="lineIndeterminate"
                                        @change="lineHandleCheckAll">
                                        全选
                                    </el-checkbox>
                                </template>
                                <el-option v-for="item in linesAndStationsArr" :label="item.label" :value="item.value"
                                    :key="item.value" />
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="站点:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                            <el-select v-model="paramsForm.stations" multiple clearable collapse-tags
                                collapse-tags-tooltip placeholder="可留空" size="small" style="width: 150px"
                                @change="changeStations">
                                <template #header>
                                    <el-checkbox v-model="stationCheckAll" :indeterminate="stationIndeterminate"
                                        @change="stationHandleCheckAll">
                                        全选
                                    </el-checkbox>
                                </template>
                                <el-option v-for="item in stationsArr" :label="item.label" :value="item.value"
                                    :key="item.value" />
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="专业:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                            <el-select v-model="paramsForm.specialties" clearable placeholder="可留空" size="small"
                                style="width: 150px" multiple collapse-tags collapse-tags-tooltip
                                @visible-change="getSpecialties" @change="changeSpecialies">
                                <template #header>
                                    <el-checkbox v-model="specCheckAll" :indeterminate="specIndeterminate"
                                        @change="specHandleCheckAll">
                                        全选
                                    </el-checkbox>
                                </template>
                                <el-option v-for="item in specialtiesArr" :label="item.label" :value="item.value"
                                    :key="item.value" />
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="子系统:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['', undefined, null]">
                            <el-select v-model="paramsForm.subsys" multiple clearable collapse-tags
                                collapse-tags-tooltip placeholder="可留空" size="small" style="width: 150px"
                                @change="changeSubsys">
                                <template #header>
                                    <el-checkbox v-model="subCheckAll" :indeterminate="subIndeterminate"
                                        @change="subHandleCheckAll">
                                        全选
                                    </el-checkbox>
                                </template>
                                <el-option v-for="item in subsysArr" :label="item.label" :value="item.value"
                                    :key="item.value" />
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="getMcsDeviceMiddle(paramsForm)" 
                         :loading = "loading"
                        >查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>
        <template #control>
            <Control :batchIsShow="batchIsShow" :downloadBoxShow="downloadBoxShow" :permObj="permObj"
                @addClick="editMdm('add', {})" @showDownload="showDownloadBox"
                @downloadExcelPaging="downloadExcelPaging(newDatasArr, 'devicesTable', '设备信息')"
                @downloadExcelAll="downloadExcelAll(datasArr, '设备信息')" @batchToggleShow="batchEdit"
                @batchDel="editSubmit('batchDel', selectDevices)" @batchUpload="batchUpload"></Control>
            <Paging :dataLength="datasLength" :countPage="countPage" :btnDisabledObj="btnDisabledObj"
                v-model:firstPage="firstPage" v-model:pageSize="pageSize" @toNext="nextPage(firstPage)"
                @toLast="lastPage(firstPage)" @toFirst="toFirstPage" @toEnd="toEndPage" @toSpecify="toSpecifyPage"
                @changePsize="changePageSize"></Paging>
        </template>
        <template #content>
            <el-table :data="newDatasArr" style="width: 100%" v-loading="loading"
                @selection-change="handleSelectionChange" id="devicesTable">
                <el-table-column type="selection" width="50" v-if="selectShow" />
                <el-table-column prop="DEVICEID" label="消防检测设备编码" width="170" />
                <el-table-column prop="CODEE" label="主控设备编码" width="150" />
                <el-table-column prop="CODEC" label="主控设备描述" width="150" />
                <el-table-column prop="STATION" label="车站" width="120" />
                <el-table-column prop="LINE" label="线路" width="60" />
                <el-table-column prop="LOC" label="站点" width="120" />
                <el-table-column prop="SPEC" label="专业" width="60" />
                <el-table-column prop="SUB" label="子系统" width="120" />
                <el-table-column fixed="right" label="Operations" min-width="60" width="210" v-perm="permObj.update">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="editMdm('update', row)" title="编辑"
                            v-perm="permObj.update">
                            <el-icon>
                                <Edit />
                            </el-icon>
                        </el-button>
                        <el-button type="warning" size="small" @click="editMdm('copy', row)" title="复制"
                            v-perm="permObj.add">
                            <el-icon>
                                <CopyDocument />
                            </el-icon>
                        </el-button>
                        <el-button type="danger" size="small" class="del" title="删除" @click="editSubmit('delete', row)"
                            v-perm="permObj.delete">
                            <el-icon>
                                <DeleteFilled />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
    </AdminSkeleton>
    <Drawer ref="drawerRef" :title="title" :size="size" @submit="editSubmit(submitType, editForm)"
        @cancel-submit="resetForm">
        <el-form :model="editForm" ref="updateFormRef" :rules="rules">
            <el-form-item label="消防检测设备编码" :label-width="formLabelWidth" prop="DEVICEID">
                <el-input v-model="editForm.DEVICEID" autocomplete="off" />
            </el-form-item>
            <el-form-item label="主控设备编码" :label-width="formLabelWidth" >
                <el-input v-model="editForm.CODEE" autocomplete="off" />
            </el-form-item>
            <el-form-item label="主控设备描述" :label-width="formLabelWidth" prop="CODEC">
                <el-input v-model="editForm.CODEC" autocomplete="off" />
            </el-form-item>
            <el-form-item label="车站" :label-width="formLabelWidth" prop="STATION">
                <el-input v-model="editForm.STATION" autocomplete="off" />
            </el-form-item>
        </el-form>
    </Drawer>
    <Dialog ref="dialogRef" :uploadKeys="uploadKeys"
        @uploadFile="uploadFile" @closeDialog="closeDialog"
        @batchUpdate="editSubmit('batchUpdate',uploadTable)"
        @batchAdd="editSubmit('batchAdd',uploadTable)"
        @downloadTemplate="downloadTemplate('upload-table','设备信息导入模板')"
    > 
        <el-table :data="uploadTable" style="width: 100%" ref="dialogTableRef" id="upload-table">
            <el-table-column prop="DEVICEID" label="消防检测设备编码" width="170" />
            <el-table-column prop="CODEE" label="主控设备编码" width="150" />
            <el-table-column prop="CODEC" label="主控设备描述" width="150" />
            <el-table-column prop="STATION" label="车站" width="120" />    
        </el-table>
    </Dialog>
</template>

<script setup>
import AdminSkeleton from '@/components/AdminSkeleton.vue'
import Paging from '@/components/Paging.vue'
import Control from '@/components/Control.vue'
import Dialog from '@/components/Dialog.vue'
import Drawer from '@/components/Drawer.vue'
import { ref, reactive, watch } from 'vue'
import { xfjcStore } from '@/stores/jcStore'
import { paging } from '@/utils/paging'
import { getLinesInfo, getSpecialtiesInfo } from '@/utils/xfjcApi/device'
import { getMcsDeviceMiddleInfo , editMcsDeviceMiddle , editManyMcsDeviceMiddle} from '@/utils/xfjcApi/McsDeviceMiddle'
import { objCopy } from '@/utils/objCopy'
import { exportClickFromTableId , exportClickFromDatas } from '@/utils/downloadExcel'
import { msgOpen } from '@/utils/msg'
import {confirm ,confirmBatch} from '@/utils/confirm'

let useJcStore = xfjcStore()

const {
    datasArr,
    datasLength,
    firstPage,
    pageSize,
    countPage,
    newDatasArr,
    btnDisabledObj,
    pagingPreprocessing,
    nextPage,
    lastPage,
    toFirstPage,
    toEndPage,
    toSpecifyPage,
    changePageSize
} = paging() //分页


//权限对象--用于控制按钮显示
const permObj = {
    add: { name: 'McsDeviceMiddle', type: 'add' },
    update: { name: 'McsDeviceMiddle', type: 'update' },
    delete: { name: 'McsDeviceMiddle', type: 'delete' }
}

//查询参数
//#region 
//线路、站点
let linesAndStationsArr = ref([])
let lineCheckAll = ref(false)
let lineIndeterminate = ref(false) //设置不确定状态，仅负责样式控制
let stationsArr = ref([])
let stationCheckAll = ref(false)
let stationIndeterminate = ref(false)

//专业、子系统
let specialtiesArr = ref([])
let specCheckAll = ref(false)
let specIndeterminate = ref(false)
let subsysArr = ref([])
let subCheckAll = ref(false)
let subIndeterminate = ref(false)


let paramsForm = reactive({
    lines: [],
    stations: [],
    specialties: [],
    subsys: [],
})

//table及查询按钮的LOADING
let loading = ref(false)

/**
 * location转换为树形
 * @param {Array} arr workType 原数组对象 
 */
const locationToTree = (arr) => {
    let line = []
    // 先把线路拿出来
    arr.forEach(item => {
        if (item.AREATYPE === '线路') {
            let lineObj = {
                label: item.DESCRIPTION,
                value: item.LOCATION,
                children: []
            }
            line.push(lineObj)
        }
    })
    // 再把站点拿出来
    line.forEach(item => {
        arr.forEach(item1 => {
            if (item.value === item1.CUST_LINENUM && item1.AREATYPE !== '线路') {
                let stationObj = {
                    label: item1.DESCRIPTION,
                    value: item1.LOCATION,
                    parent: item.value
                }
                item.children.push(stationObj)
            }
        })
    })
    // console.log(line)
    return line
}

//获取线路站点数据
const getLines = async () => {
    //获取数据
    if (!useJcStore.linesInfo.length) {
        let lines = await getLinesInfo()
        if (lines.status) {
            linesAndStationsArr.value = locationToTree(lines.resDatas.lines)
            useJcStore.setLinesInfo(linesAndStationsArr.value)
        }
    } else {
        linesAndStationsArr.value = useJcStore.linesInfo
    }
}

/**
 * 改变线路联动站点
 * @param val 选中的线路值
 */
const changeLines = (val) => {
    // console.log(val)
    // console.log(typeof val)
    // console.log(Array.isArray(val))    
    //#region  
    //单选   
    if (typeof val === 'string') {
        linesAndStationsArr.value.forEach(item => {
            // console.log(item)            
            if (item.value === val) stationsArr.value = item.children
        })
    }
    //多选 el-select组件多选后使用typeof判断为object，需要使用Array.isArray()才能判断为数组
    if (Array.isArray(val)) {
        //每次改变线路时，都要把站点清空
        paramsForm.stations = []
        stationCheckAll.value = false
        stationIndeterminate.value = false
        if (val.length === 1) {
            //取消全选
            if (linesAndStationsArr.value.length && val.length !== linesAndStationsArr.value.length) {
                lineCheckAll.value = false
                lineIndeterminate.value = true
            }
            linesAndStationsArr.value.forEach(item => {
                // console.log(item)            
                if (item.value === val[0]) stationsArr.value = item.children
            })
        }
        else if (val.length === 0) {
            stationsArr.value = []
            stationCheckAll.value = false
            stationIndeterminate.value = false
            lineCheckAll.value = false
            lineIndeterminate.value = false
        }
        else if (val.length > 1) {
            // 当val长度大于1切等于线路数组长度时，全选勾选
            if (val.length === linesAndStationsArr.value.length) {
                lineCheckAll.value = true
                lineIndeterminate.value = false
            } else {
                lineCheckAll.value = false
                lineIndeterminate.value = true
            }
            let staArrss = []
            // 当val长度大于1时，获取站点
            for (let i = 0; i < val.length; i++) {
                let staArrs = []
                for (let j = 0; j < linesAndStationsArr.value.length; j++) {
                    let staArr = []
                    if (linesAndStationsArr.value[j].value === val[i]) {
                        staArr.push(...linesAndStationsArr.value[j].children)
                        staArrs.push(...staArr)
                    }
                }
                staArrss.push(...staArrs)
            }
            stationsArr.value = staArrss
        }
    }
    //#endregion
}

//线路全选
const lineHandleCheckAll = (val) => {
    lineIndeterminate.value = false
    if (val) {
        paramsForm.lines = linesAndStationsArr.value.map((_) => _.value)
        //需要调用changeLines方法，否则会出现选中的线路没有站点的情况
        changeLines(paramsForm.lines)
    } else {
        paramsForm.lines = []
        //需要调用changeLines方法，否则会出现不选线路后站点仍存在的情况
        changeLines(paramsForm.lines)
    }
}

/**
 * 站点变更
 * @param val 选中的站点值
 */
const changeStations = (val) => {
    if (Array.isArray(val)) {
        if (val.length === 1) {
            //取消全选
            if (stationsArr.value.length && val.length !== stationsArr.value.length) {
                stationCheckAll.value = false
                stationIndeterminate.value = true
            }
        }
        else if (val.length === 0) {
            stationCheckAll.value = false
            stationIndeterminate.value = false
        }
        else if (val.length > 1) {
            // 当val长度大于1切等于站点数组长度时，全选勾选
            if (val.length === stationsArr.value.length) {
                stationCheckAll.value = true
                stationIndeterminate.value = false
            } else {
                stationCheckAll.value = false
                stationIndeterminate.value = true
            }
        }
    }
}

/**
 * 站点全选
 * @param val 站点全选值
 */
const stationHandleCheckAll = (val) => {
    stationIndeterminate.value = false
    if (val) {
        paramsForm.stations = stationsArr.value.map((_) => _.value)
    } else {
        paramsForm.stations = []
    }
}

/**
 * 专业子系统转换为树形
 * @param spec 专业数组
 * @param sub 子系统数组
 */
const specAndSubToTree = (spec, sub) => {
    let specArr = []
    let subs = ['FASFGW', 'FASFSB', 'FASFYG', 'FASMOS', 'GQTSFD', 'FASQSB', 'FASQXF', 'FASXFS', 'FASFHH']
    spec.forEach(item => {
        let specObj = {
            label: item.SPEC_DESC,
            value: item.CUST_SPECNUM,
            children: []
        }
        specArr.push(specObj)
    })
    sub.forEach(item => {
        specArr.forEach(item1 => {
            if (item1.value === item.CUST_SPECNUM && subs.includes(item.CUST_SUBSYS)) {
                let subObj = {
                    label: item.SUB_DESC,
                    value: item.CUST_SUBSYS,
                    parent: item1.value
                }
                item1.children.push(subObj)
            }
        })
    })
    // console.log(specArr)
    return specArr

}

//获取专业及子系统数据
const getSpecialties = async () => {
    if (!useJcStore.specialtiesInfo.length) {
        //获取专业
        let specAndSub = await getSpecialtiesInfo()
        if (specAndSub.status) {
            specialtiesArr.value = specAndSubToTree(specAndSub.resDatas.specialties, specAndSub.resDatas.subsys)
            useJcStore.setSpecialtiesInfo(specialtiesArr.value)
        }
    } else {
        specialtiesArr.value = useJcStore.specialtiesInfo
    }
}

/**
 * 改变专业联动子系统
 * @param val 选中的专业值
*/
const changeSpecialies = (val) => {
    if (typeof val === 'string') {
        specialtiesArr.value.forEach(item => {
            // console.log(item)
            if (item.value === val) subsysArr.value = item.children
        })
    }
    if (Array.isArray(val)) {
        //每次改变专业时，都要把子系统清空
        paramsForm.subsys = []
        subCheckAll.value = false
        subIndeterminate.value = false
        if (val.length === 1) {
            //取消全选
            if (specialtiesArr.value.length && val.length !== specialtiesArr.value.length) {
                specCheckAll.value = false
                specIndeterminate.value = true
            }
            specialtiesArr.value.forEach(item => {
                // console.log(item)
                if (item.value === val[0]) subsysArr.value = item.children
            })
        }
        else if (val.length === 0) {
            subsysArr.value = []
            subCheckAll.value = false
            subIndeterminate.value = false
            specCheckAll.value = false
            specIndeterminate.value = false
        }
        else if (val.length > 1) {
            // 当val长度大于1切等于专业数组长度时，全选勾选
            if (val.length === specialtiesArr.value.length) {
                specCheckAll.value = true
                specIndeterminate.value = false
            } else {
                specCheckAll.value = false
                specIndeterminate.value = true
            }
            let subArrss = []
            // 当val长度大于1时，获取子系统
            for (let i = 0; i < val.length; i++) {
                let subArrs = []
                for (let j = 0; j < specialtiesArr.value.length; j++) {
                    let subArr = []
                    if (specialtiesArr.value[j].value === val[i]) {
                        subArr.push(...specialtiesArr.value[j].children)
                        subArrs.push(...subArr)
                    }
                }
                subArrss.push(...subArrs)
            }
            subsysArr.value = subArrss
        }
    }
}

/**
 * 专业全选
 * @param val 专业全选值
 */
const specHandleCheckAll = (val) => {
    specIndeterminate.value = false
    if (val) {
        paramsForm.specialties = specialtiesArr.value.map((_) => _.value)
        changeSpecialies(paramsForm.specialties)
    } else {
        paramsForm.specialties = []
        changeSpecialies(paramsForm.specialties)
    }
}

/**
 * 子系统变更
 * @param val 选中的子系统值
 */
const changeSubsys = (val) => {
    if (Array.isArray(val)) {
        if (val.length === 1) {
            //取消全选
            if (subsysArr.value.length && val.length !== subsysArr.value.length) {
                subCheckAll.value = false
                subIndeterminate.value = true
            }
        }
        else if (val.length === 0) {
            subCheckAll.value = false
            subIndeterminate.value = false
        }
        else if (val.length > 1) {
            // 当val长度大于1切等于子系统数组长度时，全选勾选
            if (val.length === subsysArr.value.length) {
                subCheckAll.value = true
                subIndeterminate.value = false
            } else {
                subCheckAll.value = false
                subIndeterminate.value = true
            }
        }
    }
}

/**
 * 子系统全选
 * @param val 子系统全选值
 */
const subHandleCheckAll = (val) => {
    subIndeterminate.value = false
    if (val) {
        paramsForm.subsys = subsysArr.value.map((_) => _.value)
    } else {
        paramsForm.subsys = []
    }
}

/**
 * 查询主控设备中间表
 * @param form 查询参数
 */
const getMcsDeviceMiddle = async (form) => {
    // console.log(form)
    loading.value = true
    let res = await getMcsDeviceMiddleInfo(form)
    // console.log(res)
    pagingPreprocessing(res.resDatas.mcsDeviceMiddleInfo) //分页前置处理
    loading.value = false
}

//#endregion

//编辑设备信息
//#region 
let title = ref("")
let size = ref("40%")
let formLabelWidth = ref("150")

//编辑用户信息
let drawerRef = ref(null) //组件ref
let oldDevice = reactive({
    DEVICEID: "",
    CODEE: "",
    CODEC: "",
    STATION: "",
})//用于存储未修改前设备信息
let editForm = reactive({
    DEVICEID: "",
    CODEE: "",
    CODEC: "",
    STATION: "",
})
//提交类型
let submitType = ref('')
//表单验证ref
let updateFormRef = ref(null)
//输入框验证规则
let rules = reactive({
    DEVICEID: [
        { required: true, message: '请输入消防检测描述设备编码', trigger: 'blur' },
    ],
    STATION: [
        { required: true, message: '请输入车站', trigger: 'blur' },
    ],
    CODEC: [
        { required: true, message: '请输入主控设备描述', trigger: 'blur' },
    ],
})

//重置表单
const resetForm = () => {
    if (submitType.value === 'update' || submitType.value === 'copy') {
        editForm = objCopy(oldDevice, editForm)
    } else if (submitType.value === 'add') {
        editForm = reactive({
            DEVICEID: "",
            CODEE: "",
            CODEC: "",
            STATION: "",
        })
    }
}

/**
 * 处理单个设备编辑、删除
 * @param type 操作类型，add：新增，update：编辑，del：删除
 * @param row 
 */
const editMdm = (type, row) => {
    // console.log(type)
    // console.log(row)
    submitType.value = type
    if (type === 'update') {
        drawerRef.value.open()
        title.value = "编辑"
        editForm = row
        //存储未修改前用户信息
        oldDevice = objCopy(row, oldDevice)
    }
    if (type === 'add') {
        drawerRef.value.open()
        title.value = "新增"
        resetForm()
    }
    if (type === "copy") {
        drawerRef.value.open()
        title.value = "复制"
        editForm = objCopy(row, editForm)
        editForm.DEVICEID += "_副本"
    }
}

//#endregion

//批量处理弹出层
//#region 
let batchIsShow = ref(false) //展示批量上传、批量删除状态
let selectShow = ref(false) //展示批量勾选状态
let selectDevices = ref([]) //选中的设备行数据
let dialogRef = ref(null) //组件ref
let uploadKeys = ref([
    "DEVICEID",
    "CODEE",
    "CODEC",
    "STATION",
]) //上传的字段

const batchEdit = ()=>{   
    if(newDatasArr.value.length) selectShow.value = !selectShow.value
    batchIsShow.value = !batchIsShow.value
}

/**
 * 表格选中行数据变化时触发的方法
 * @param val 选中的设备行数据
 */
const handleSelectionChange = (val)=>{
    selectDevices.value = val 
}

//批量上传
let uploadTable = ref([])
const batchUpload = ()=>{
    // console.log('batchUpload');
    dialogRef.value.open()       
}

//关闭
const closeDialog = () => {
    uploadTable = ref([])
    dialogRef.value.close()
}

//接收子组件传递的excel数据，渲染至界面
let dialogTableRef = ref(null)
const uploadFile = (e)=>{    
    console.log(e.value)           
    uploadTable = e.value   
}

//下载
let downloadBoxShow = ref(false) //展示下载框状态
const showDownloadBox = ()=>{
    downloadBoxShow.value = !downloadBoxShow.value
}
/** 
 * 下载当前页
 * @param {Array} data 导出的数据数组对象
 * @param {String} tableId table标签的ID
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelPaging = (data,tableId,fileName)=>{
    data.length ? exportClickFromTableId(tableId,fileName) : msgOpen("无数据可供下载，请先查询数据")
}
/**
 * 下载全部
 * @param {Array} data 导出的数据数组对象(未进行分页)
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelAll = (data,fileName)=>{   
    if(data.length){
        let newData = JSON.parse(JSON.stringify(data)) //深拷贝       
        exportClickFromDatas(newData,fileName)
    }else{
        msgOpen("无数据可供下载，请先查询数据")
    }
}

/**
 * 导入模版下载
 * @param tableId table标签的ID
 * @param fileName 需要命名的文件名
 */
 const downloadTemplate = (tableId,fileName)=>{
    // console.log(tableId)
    exportClickFromTableId(tableId,fileName)
}

//#endregion

/**
 * 处理批量设备编辑、删除
 * @param type 操作类型，add：新增，update：编辑，delete：删除，batchAdd：批量新增，batchUpdate：批量更新，batchDel：批量删除
 * @param data 设备数据
 */
const editSubmit = async (type, data) => {
    console.log(type)
    console.log(data)
    if(type === 'delete'){
        let res = await confirm(data.DEVICEID)
        if(res){
            let newMcsDeviceMiddle = await editMcsDeviceMiddle(type,data)
            newMcsDeviceMiddle.status ? msgOpen(newMcsDeviceMiddle.msg,'success') : msgOpen(newMcsDeviceMiddle.msg)
            getMcsDeviceMiddle(paramsForm)
        }
    }

    if(type === 'add' || type === 'update' || type === 'copy'){
        updateFormRef.value.validate(async (valid) => {
            if(!valid){
                return false
            }else{
                let newMcsDeviceMiddle = await editMcsDeviceMiddle(type,data)
                console.log(newMcsDeviceMiddle);
                drawerRef.value.hideLoading()
                drawerRef.value.close()
                newMcsDeviceMiddle.status ? msgOpen(newMcsDeviceMiddle.msg,'success') : msgOpen(newMcsDeviceMiddle.msg)
                getMcsDeviceMiddle(paramsForm) 
                resetForm() 
            }
        })        
    }

    if(type === 'batchDel'){
        if(!data.length){
            msgOpen('未进行勾选，请勾选！')
        }else{
            console.log(data)            
            let idsArrs = []
            data.forEach(item => {
                let idsArr = []
                idsArr.push(item.DEVICEID)
                idsArrs.push(idsArr)
            })
            let res = await confirmBatch(idsArrs.length)
            if(res){
                let newDevice = await editManyMcsDeviceMiddle(type,idsArrs)
                newDevice.status ? msgOpen(newDevice.msg,'success') : msgOpen(newDevice.msg)
                getMcsDeviceMiddle(paramsForm)
            }
        }
    } 

    if(type === 'batchAdd' || type === 'batchUpdate'){
        let rowsArr = ref([]) 
        let editBatchStatus = ref(true)
        for(let i = 0;i < data.length;i++){           
            if(type === 'batchUpdate' && !data[i].DEVICEID){
                msgOpen("更新设备，请填写ID！")
                editBatchStatus.value = false
                break
            }else if(type === 'batchAdd' && !data[i].DEVICEID){
                msgOpen("新增设备，必须填写DEVICEID！")
                editBatchStatus.value = false
                break  
            }else{
                let row
                if(type === 'batchAdd'){
                    row = Object.values(data[i]) //将对象值转成数组
                }else{
                    row = data[i] //传给后端(ORACLE也可接收数组对象，处理时SQL绑定变量须于数组对象内的KEY值一致)                  
                }                               
                rowsArr.value.push(row)
            }
        } 
        if(editBatchStatus.value){
            let newMcsDeviceMiddle = await editManyMcsDeviceMiddle(type,rowsArr.value)
            console.log(newMcsDeviceMiddle)
            dialogRef.value.close()
            uploadTable = ref([])
            newMcsDeviceMiddle.status ? msgOpen(newMcsDeviceMiddle.msg,'success') : msgOpen(newMcsDeviceMiddle.msg)
            getMcsDeviceMiddle(paramsForm) 
        }
    }

}

watch([uploadTable],(newTable, oldTable) => {
    // console.log(newTable[0]);
    uploadTable.value = newTable[0]
})
</script>

<style lang="less" scoped>
.params-form {
    height: 100%;
    width: 100%;

    .el-form {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;

        .el-form-item {
            margin-bottom: 0;
            margin-right: .3125rem;
        }
    }
}

.el-table {
    height: 95%;
}
</style>